package cn.fzkj.gulimall.member.service.impl;

import cn.fzkj.gulimall.member.dao.MemberLevelDao;
import cn.fzkj.gulimall.member.dao.OauthUserDao;
import cn.fzkj.gulimall.member.entity.OauthUserEntity;
import cn.fzkj.gulimall.member.vo.base.SocialUser;
import cn.fzkj.gulimall.member.exception.PhoneExistException;
import cn.fzkj.gulimall.member.exception.UsernameExistException;
import cn.fzkj.gulimall.member.vo.MemberLoginVo;
import cn.fzkj.gulimall.member.vo.MemberRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.fzkj.common.utils.PageUtils;
import cn.fzkj.common.utils.Query;

import cn.fzkj.gulimall.member.dao.MemberDao;
import cn.fzkj.gulimall.member.entity.MemberEntity;
import cn.fzkj.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;
    @Autowired
    private OauthUserDao oauthUserDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public boolean register(MemberRegisterVo vo) {

        MemberEntity entity = new MemberEntity();
        long defaultLevel = memberLevelDao.getDefaultLevel();
        entity.setLevelId(defaultLevel);

        // 手机号和账号需要判断是否注册过
        checkPhoneUnique(vo.getPhoneNum());
        entity.setMobile(vo.getPhoneNum());

        checkUsernameUnique(vo.getUserName());
        entity.setUsername(vo.getUserName());

        // 密码需要加密
        String password = new BCryptPasswordEncoder().encode(vo.getPassword());
        entity.setPassword(password);

        return this.baseMapper.insert(entity) > 0;
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginAcct = vo.getLoginAcct();

        MemberEntity entity = this.baseMapper.selectOne(
                new QueryWrapper<MemberEntity>()
                        .eq("username", loginAcct)
                        .or()
                        .eq("mobile", loginAcct)
        );
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (entity != null && encoder.matches(vo.getPassword(), entity.getPassword())){
            return entity;
        }
        return null;
    }

    @Override
    public MemberEntity login(SocialUser user) {

        // 用户是否注册过
        OauthUserEntity oauthUser = oauthUserDao.selectOne(new QueryWrapper<OauthUserEntity>().eq("openid", user.getUserId()));
        if (oauthUser != null){
            // 登陆过
            return this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("id", oauthUser.getUserid()));
        }else {
            // 注册
            MemberEntity member = new MemberEntity();
            member.setNickname(user.getUserName());
            member.setEmail(user.getEmail());
            member.setLevelId(1L);
            member.setUsername(user.getUserName());
            this.baseMapper.insert(member);

            // new
            oauthUser = new OauthUserEntity();
            oauthUser.setUserid(member.getId());
            oauthUser.setOpenid(user.getUserId());
            oauthUser.setLoginType(user.getLoginType());
            oauthUserDao.insert(oauthUser);

            return member;
        }
    }
    
    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Long mobileCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobileCount > 1){
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        Long userCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (userCount > 1){
            throw new UsernameExistException();
        }

    }
}